package com.mathlearning.auth.service;

import com.mathlearning.auth.common.BusinessException;
import com.mathlearning.auth.dto.user.FollowResponse;
import com.mathlearning.auth.entity.Follow;
import com.mathlearning.auth.repository.FollowRepository;
import com.mathlearning.auth.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FollowService {

    private static final Logger logger = LoggerFactory.getLogger(FollowService.class);

    @Autowired
    private FollowRepository followRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 关注/取消关注用户
     */
    @Transactional
    public FollowResponse toggleFollow(Long followerId, Long followingId) {
        // 参数验证
        if (followerId.equals(followingId)) {
            throw new BusinessException("不能关注自己");
        }

        // 检查目标用户是否存在
        if (!userRepository.existsById(followingId)) {
            throw new BusinessException("用户不存在");
        }

        // 检查是否已关注
        boolean isFollowed = followRepository.existsByFollowerIdAndFollowingId(followerId, followingId);

        if (isFollowed) {
            // 已关注，执行取消关注
            Follow follow = followRepository.findByFollowerIdAndFollowingId(followerId, followingId)
                    .orElseThrow(() -> new BusinessException("关注记录不存在"));
            followRepository.delete(follow);
            logger.info("取消关注成功 - 关注者ID: {}, 被关注者ID: {}", followerId, followingId);
            return new FollowResponse(false);
        } else {
            // 未关注，执行关注
            Follow follow = new Follow();
            follow.setFollowerId(followerId);
            follow.setFollowingId(followingId);
            followRepository.save(follow);
            logger.info("关注成功 - 关注者ID: {}, 被关注者ID: {}", followerId, followingId);
            return new FollowResponse(true);
        }
    }
}








